package com.cincc.cincc_pbx.common;


import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.cincc.cincc_pbx.constant.CallConstant;
import com.cincc.cincc_pbx.model.EventBusModel;
import com.cincc.cincc_pbx.ui.CallActivity;
import com.cincc.siphone.core.SipCoreCall;
import com.cincc.siphone.core.SipCoreEvent;
import com.cincc.siphone.core.SipCoreEvent.CallState;
import com.cincc.siphone.core.SipPhoneCtrl;

import org.greenrobot.eventbus.EventBus;

/**
 * @company Name:
 * @author: sky
 * @creatDate: 2022/7/19 16:55
 * @className: CallUtil
 * @description:
 * @modified By:
 * @modifyDate:
 */
public class CallUtil {

    private static final String TAG = "CallUtil";
    private int webSocketState = 200;
    private SipPhoneCtrl mSipPhoneCtrl = SipPhoneCtrl.Instance();

    private static CallUtil instance = new CallUtil();

    private CallUtil() {
    }

    public static CallUtil getInstance() {
        return instance;
    }

    String sipAccount = "";

    public void register(Activity context) {
//        String sipAccount = "0000026666666007";
//        String sipPassword = "qwerty123";

        sipAccount = MyUtils.getSipAccount();
//        String sipAccount = CallConstant.loginModel.getTelPhone();
        String sipPassword = CallConstant.loginModel.getPasswd();

        if (!TextUtils.isEmpty(sipPassword)) {
            CallUtil.getInstance().initSipParam(CallConstant.SIP_IP, CallConstant.SIP_PORT, sipAccount, sipPassword);
            CallUtil.getInstance().bindSipEvent(context);
            CallUtil.getInstance().doRegister(context);
        }
    }

    /**
     * 析构SDK
     */
    public void UnInitial() {
        mSipPhoneCtrl.UnInitial();
    }


    /**
     * 初始化Sip参数
     */
    public void initSipParam(String sipIp, String sipPort, String sipAccount, String sipPassword) {
        Log.d("CallUtil", "SDK版本信息为===>" + mSipPhoneCtrl.GetVersion());

        //"Ulaw;0", "Alaw;8", "ILbc;102", "Opus;120", "Agora;121",XYlink;122"
        int mDefaultCodec = 120;
        //"H264;127", "VP8;100", "VP9;101"
        int mDefaultVCodec = 127;
        boolean mSupportVideo = true;
        int mSipHeartBeatInterval = 15;
        //0: nolog 1:sipcore 2:sipstack 3:all
        int mTraceFlag = 3;
        //1:writelog 2:nologfile
        int mFileFlag = 1;

        //主叫号码设置
        mSipPhoneCtrl.SetNumber(sipAccount);
        mSipPhoneCtrl.SetAuthName(sipAccount);
        mSipPhoneCtrl.SetPassWord(sipPassword);
        mSipPhoneCtrl.SetDomain(sipIp);
        mSipPhoneCtrl.SetServer(sipIp);
        mSipPhoneCtrl.SetServerPort(Integer.parseInt(sipPort));

        mSipPhoneCtrl.SetTraceFlag(mTraceFlag);
        mSipPhoneCtrl.SetFileFlag(mFileFlag);
//        mSipPhoneCtrl.SetDefaultCodec(mDefaultCodec);
        mSipPhoneCtrl.SetDefaultVCodec(mDefaultVCodec);
        mSipPhoneCtrl.SetSurpportVedio(false);
        mSipPhoneCtrl.SetSipHeartBeatInterval(mSipHeartBeatInterval);
        //option方式发送心跳
        mSipPhoneCtrl.SetSipHeartBeatType(1);
        mSipPhoneCtrl.SetTimerType(SipCoreEvent.TimerType.TimerType_handle);
        mSipPhoneCtrl.SetAutoRegister(false);

        mSipPhoneCtrl.SetXPath("sbc");
        mSipPhoneCtrl.SetTransferMode(SipCoreEvent.TransferMode.TransferMode_WebSocket);
        mSipPhoneCtrl.setGmMode(false);
        mSipPhoneCtrl.SetSdkId("acf1e9d0faa428be7fc12c2b6775fe2d");
        mSipPhoneCtrl.SetCallStatics(true);

        mSipPhoneCtrl.SetVideoMode(SipCoreEvent.VideoMode.Webrtc_Fit);
        mSipPhoneCtrl.SetMeidaType(SipCoreEvent.MediaType.WebrtcVoice);
    }


    /**
     * 进行SIP注册
     *
     * @param context
     */
    public void doRegister(Activity context) {
        mSipPhoneCtrl.Initial(context, i -> {
            Log.e("CallActivity", "onInitResult===>" + i);
            if (i == 200) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSipPhoneCtrl.Register();
                    }
                });
            } else {
                Log.e("CallActivity", "Sip初始化失败");
            }
        });
    }


    /**
     * 拨打号码
     */
    public void makeCall(String callNumber) {
        if (webSocketState == 200) {
            String extraHeader = "";
            if (mSipPhoneCtrl.DoCall(String.format("%s@%s", callNumber, mSipPhoneCtrl.GetServer()), extraHeader)) {
                //呼叫成功
            } else {
                if (CallActivity.GetInstance() != null) {
                    CallActivity.GetInstance().setCallStateText("呼叫状态错误，不允许外呼");
                }
            }
        }
    }

    public void answer() {
        mSipPhoneCtrl.Answer();
    }

    public void reject() {
        mSipPhoneCtrl.Disconnect();
    }

    /**
     * 绑定sip的通话事件
     */
    public void bindSipEvent(Activity context) {
        mSipPhoneCtrl.RegisterEvent(new SipPhoneCtrl.IEvent() {

            @Override
            public void onCallStateChanged(SipCoreCall sipCoreCall, SipCoreEvent.CallState callState, String message) {
                Log.e("CallActivity", String.format("onCallStateChanged(%s,%s)",
                        callState.toString(), sipCoreCall.mediaType.toString()));

                if (callState == CallState.OutgoingProgress) {
                    Log.e("CallActivity", String.format("外呼中:[%s]", sipCoreCall.sNum));
                    if (CallActivity.GetInstance() != null) {
                        CallActivity.GetInstance().setCallStateText("外呼中");
                    }
                } else if (callState == CallState.OutgoingRinging) {
                    Log.e("CallActivity", String.format("外呼对方振铃:[%s]", sipCoreCall.sNum));
                    if (CallActivity.GetInstance() != null) {
                        CallActivity.GetInstance().setCallStateText("外呼对方振铃");
                    }
                } else if (callState == CallState.Connected) {
                    Log.e("CallActivity", String.format("接通:[%s]", sipCoreCall.sNum));
                    if (CallActivity.GetInstance() != null) {
                        CallActivity.GetInstance().setCallStateText("已接通");
                        CallActivity.GetInstance().connect();
                    }
                } else if (callState == CallState.CallEnd || callState == CallState.CallReleased) {
                    EventBus.getDefault().post(new EventBusModel(CallConstant.REFRESH_RECORD_EVENT, null));
                    if (CallActivity.GetInstance() != null) {
                        CallActivity.GetInstance().finishCallPage();
                    }
                } else if (callState == CallState.Error) {
                    Log.e("CallActivity", String.format("error:[%d:%s]", sipCoreCall.nCode, sipCoreCall.sDescription));
                    EventBus.getDefault().post(new EventBusModel(CallConstant.REFRESH_RECORD_EVENT, null));
                    if (CallActivity.GetInstance() != null) {
                        CallActivity.GetInstance().finishCallPage();
                    }
                } else if (callState == CallState.IncomingReceived) {
                    EventBus.getDefault().post(new EventBusModel(CallConstant.INVITE_CALL, sipCoreCall.sNum));
                }
            }

            @Override
            public void onMediaConsultation(String key, String param) {
                //加速通道参数回调
                Log.e("CallActivity", String.format("onMediaConsultation(%s,%s)", key, param));
            }

            @Override
            public void onFacePositionChanged(int i, int i1, int faces) {
                //不加速通道的人脸识别回调
                Log.e("CallActivity", "非加速通道检测到人脸：" + faces + "时间戳：" + System.currentTimeMillis());
            }

            @Override
            public void onMessage(int i, String s) {
                //带内通信
            }

            @Override
            public void onInitialStatusChange(int i, String s) {
                webSocketState = i;
            }

            @Override
            public void onScreenRecord(String s) {
            }

            @Override
            public void onInfo(String s, String s1) {

            }

            @Override
            public void onDebugEvent(String s, String s1) {
                Log.e("CallUtil", "onDebugEvent===>s: " + s + ";     s1: " + s1);
            }

            @Override
            public void onMediaStatics(SipCoreEvent.VedioInfo vedioInfo) {
            }

            @Override
            public void onRegistrationStateChanged(SipCoreEvent.RegistrationState registrationState, String s) {
                Log.e("CallActivity", "注册状态===>" + registrationState);
                if (registrationState == SipCoreEvent.RegistrationState.RegistrationOk) {
                    //Toast.makeText(context, sipAccount + "注册成功", Toast.LENGTH_LONG).show();
                } else if (registrationState == SipCoreEvent.RegistrationState.RegistrationFailed) {
                    String msg = "分机注册失败,分机号:" + sipAccount + ",密码:" + CallConstant.loginModel.getPasswd() + ",sipIp:" + CallConstant.SIP_IP + ",sipPort:" + CallConstant.SIP_PORT;
                    Log.e(TAG, msg);
                    Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

}
